import { Popover } from 'antd'
import type { ReactElement } from 'react'
import { cloneElement, useEffect, useState } from 'react'
import { useSnapshot } from 'valtio'
import {
  createId,
  searchId,
} from '@/utils'
import { componentPathState, dependencyConfigState, jsonSchema } from '@/store'

function AddWidget(props: {
  slotId?: string // 嵌套在哪个组件的id
  children?: ReactElement
}) {
  const { slotId: outsideSlotId } = props
  const [open, setOpen] = useState(false)
  const [slotId, setSlotId] = useState<string>()

  const dependencyConfigSnap = useSnapshot(
    dependencyConfigState,
  ).dependencyConfigState

  useEffect(() => {
    const simulator = document.getElementById(
      'sanbox-simulator',
    ) as HTMLIFrameElement
    if (simulator) {
      const bodyClick = () => {
        setOpen(false)
      }
      simulator?.contentDocument?.addEventListener('click', bodyClick)
      return () => {
        simulator?.contentDocument?.removeEventListener('click', bodyClick)
      }
    }
  }, [])

  if (!props.children)
    return null

  return (
    <Popover
      overlayClassName="p-0"
      style={{ padding: 0 }}
      overlayInnerStyle={{ padding: 0, borderRadius: 8 }}
      overlayStyle={{ padding: 0 }}
      arrow={false}
      placement="bottomLeft"
      trigger={['click']}
      open={open}
      onOpenChange={(vis) => {
        setOpen(vis)
        if (vis && outsideSlotId)
          setSlotId(outsideSlotId)
      }}
      content={
        <div className="w-350px min-h-200px z-9999999999999 p-15px">
          {dependencyConfigSnap.map((dependencyItem, depsList) => {
            return (dependencyItem.moduleConfig || []).length > 0 ? (
              <div key={dependencyItem.libraryName}>
                <div className="m-0 text-#2558fb text-1 text-14px">
                  {dependencyItem.libraryName}
                </div>
                <div className="grid grid-cols-4 gap-4px">
                  {dependencyItem.moduleConfig!.map((componentItem, idx2) => {
                    const {
                      hasSlot,
                      formPropsConfig,
                      defaultProps,
                      moduleName,
                      isNative,
                    } = componentItem
                    return (
                      <div
                        className="btn flex-1 text-2"
                        onClick={() => {
                          const id = createId()
                          // 把组件添加进去
                          const targetItem: (typeof jsonSchema.value)['componentsTree'][0]
                            = searchId(
                              jsonSchema.value.componentsTree,
                              outsideSlotId || slotId,
                            )

                          if (!targetItem)
                            return

                          const item = {
                            $componentName: moduleName,
                            componentid: id,
                            props: defaultProps,
                            destructuring: true,
                            isNative,
                            hasSlot:
                              typeof hasSlot !== 'undefined' ? hasSlot : true,
                          } as (typeof jsonSchema.value)['componentsTree'][0]

                          componentPathState.componentPath[id] = {
                            libraryName: dependencyItem.libraryName,
                            path: '', // 用作所有搜素
                            moduleName,
                            formPropsConfig: formPropsConfig as any,
                          }

                          const childrenVal = targetItem.children

                          if (targetItem.children) {
                            if (Array.isArray(childrenVal)) {
                              targetItem.children.push(item)
                            }
                            else {
                              // 添加 node props
                              const id = createId()
                              // 字符串 children
                              targetItem.children = [
                                {
                                  $componentName: 'div',
                                  componentid: id,
                                  children: childrenVal,
                                  hasSlot: true,
                                },
                                item,
                              ]
                            }
                          }
                          else if (!targetItem.children) {
                            targetItem.children = [item]
                          }
                          // 添加依赖关系
                          if (
                            jsonSchema.value.componentsMap.filter(
                              item => item.$componentName === moduleName,
                            ).length === 0
                          ) {
                            jsonSchema.value.componentsMap.push({
                              $componentName: moduleName,
                              package:
                                dependencyItem.libraryGlobalImport
                                || dependencyItem.libraryName,
                              destructuring: true,
                              formPropsConfig: formPropsConfig as any,
                            })
                          }
                          setOpen(false)
                        }}
                        key={componentItem.moduleName}
                      >
                        {componentItem.moduleName}
                      </div>
                    )
                  })}
                </div>
              </div>
            ) : null
          })}
        </div>
      }
    >
      {cloneElement(props.children)}
    </Popover>
  )
}

export default AddWidget
